package org.jsola.hr.service.impl;

import org.jsola.common.PageKit;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.ISaleRebatesRulesDAO;
import org.jsola.hr.dto.SaleRebatesRulesAddDTO;
import org.jsola.hr.dto.SaleRebatesRulesUpdateDTO;
import org.jsola.hr.entity.CompanySaleRebatesRulesDO;
import org.jsola.hr.entity.SaleRebatesRulesDO;
import org.jsola.hr.query.SaleRebatesRulesQuery;
import org.jsola.hr.service.ICompanySaleRebatesRulesService;
import org.jsola.hr.service.ISaleRebatesRulesService;
import org.jsola.hr.vo.SaleRebatesRulesListVO;
import org.jsola.hr.vo.SaleRebatesRulesVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 返费规则
 *
 * @author zhr
 */
@Service("hrSaleRebatesRulesServiceImpl")
public class SaleRebatesRulesServiceImpl implements ISaleRebatesRulesService {

    @Autowired
    private ISaleRebatesRulesDAO saleRebatesRulesDAO;

    @Autowired
    private ICompanySaleRebatesRulesService companySaleRebatesRulesService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public SaleRebatesRulesVO save(SaleRebatesRulesAddDTO saleRebatesRulesAddDTO, TokenUser tokenUser) {
        checkName(saleRebatesRulesAddDTO.getRulesName(), null, tokenUser.getSiteId());
        // 转DO
        SaleRebatesRulesDO saleRebatesRulesDO = saleRebatesRulesAddDTO.to(SaleRebatesRulesDO.class);
        // 保存
        saleRebatesRulesDO = save(saleRebatesRulesDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return saleRebatesRulesDO.to(SaleRebatesRulesVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(SaleRebatesRulesUpdateDTO saleRebatesRulesUpdateDTO, TokenUser tokenUser) {
        checkName(saleRebatesRulesUpdateDTO.getRulesName(), saleRebatesRulesUpdateDTO.getId(), tokenUser.getSiteId());
        //转DO
        SaleRebatesRulesDO saleRebatesRulesDO = saleRebatesRulesUpdateDTO.to(SaleRebatesRulesDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(saleRebatesRulesDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... saleRebatesRulesIds) {
        List<String> rulesIdList = Arrays.asList(saleRebatesRulesIds);
        // 查询返费规则绑定的用工单位,有则不允许删除
        for (String rulesId : rulesIdList) {
            List<CompanySaleRebatesRulesDO> companySaleRebatesRules = companySaleRebatesRulesService
                    .selectByRulesId(rulesId, tokenUser);
            if(!CollectionUtils.isEmpty(companySaleRebatesRules)){
                throw new ParamException("提成规则下绑定了用工单位,请在用工单位详情下取消绑定");
            }
        }
        companySaleRebatesRulesService.deleteByRulesIdList(rulesIdList);
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) saleRebatesRulesIds);
    }


    @Override
    public SaleRebatesRulesVO selectById(String saleRebatesRulesId, String siteId) {
        SaleRebatesRulesDO saleRebatesRulesDO = selectDOById(saleRebatesRulesId, siteId);
        if (saleRebatesRulesDO == null) {
            return null;
        }
        return saleRebatesRulesDO.to(SaleRebatesRulesVO.class);
    }

    @Override
    public List<SaleRebatesRulesListVO> select(SaleRebatesRulesQuery saleRebatesRulesQuery, String siteId) {
        List<SaleRebatesRulesDO> saleRebatesRulesDOList = selectDO(saleRebatesRulesQuery, siteId);
        if (CollectionUtils.isEmpty(saleRebatesRulesDOList)) {
            return saleRebatesRulesDOList == null ? null : new ArrayList<>();
        }
        return saleRebatesRulesDOList.stream()
                .map(saleRebatesRulesDO -> saleRebatesRulesDO.to(SaleRebatesRulesListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(SaleRebatesRulesQuery saleRebatesRulesQuery, String siteId) {
        Example example = buildExample(saleRebatesRulesQuery, siteId);
        return saleRebatesRulesDAO.selectCountByExample(example);
    }

    @Override
    public Page<SaleRebatesRulesListVO> selectPage(SaleRebatesRulesQuery saleRebatesRulesQuery, String siteId) {
        Example example = buildExample(saleRebatesRulesQuery, siteId);
        Page<SaleRebatesRulesDO> page = saleRebatesRulesDAO.selectPageByExample(example,
                saleRebatesRulesQuery.getPageNo(),
                saleRebatesRulesQuery.getPageSize());

        return page.to(SaleRebatesRulesListVO.class);
    }

    @Override
    public SaleRebatesRulesDO selectDOById(String saleRebatesRulesId, String siteId) {
        return listById(saleRebatesRulesId, siteId);
    }

    @Override
    public List<SaleRebatesRulesDO> selectDO(SaleRebatesRulesQuery saleRebatesRulesQuery, String siteId) {
        Example example = buildExample(saleRebatesRulesQuery, siteId);
        return saleRebatesRulesDAO.selectByExample(example);
    }

    @Override
    public List<SaleRebatesRulesDO> selectSiteRebatesRules(SaleRebatesRulesQuery saleRebatesRulesQuery, TokenUser tokenUser) {
        Example example = new Example(SaleRebatesRulesDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        if (!StringUtils.isEmpty(saleRebatesRulesQuery.getRulesName())) {
            example.and().andLike("rulesName", "%" + saleRebatesRulesQuery.getRulesName() + "%");
        }
        return saleRebatesRulesDAO.selectByExample(example);
    }

    @Override
    public Page<SaleRebatesRulesListVO> selectBindCompany(SaleRebatesRulesQuery saleRebatesRulesQuery, TokenUser tokenUser) {
        List<SaleRebatesRulesListVO> resultList = new ArrayList<>();
        List<SaleRebatesRulesListVO> selectList = saleRebatesRulesDAO
                .selectBindCompany(saleRebatesRulesQuery, tokenUser.getSiteId());
        Map<String, List<SaleRebatesRulesListVO>> resultMap = selectList.stream()
                .collect(Collectors.groupingBy(SaleRebatesRulesListVO::getCompanyId));
        for (String companyId : resultMap.keySet()) {
            List<SaleRebatesRulesListVO> saleRebatesRulesList = resultMap.get(companyId);
            List<String> saleNameList = saleRebatesRulesList.stream()
                    .map(SaleRebatesRulesListVO::getSaleName)
                    .filter(saleName ->!StringUtils.isEmpty(saleName)).collect(Collectors.toList());
            SaleRebatesRulesListVO saleRebatesRules = new SaleRebatesRulesListVO();
            BeanUtils.copyProperties(saleRebatesRulesList.get(0), saleRebatesRules);
            saleRebatesRules.setSaleName(CollectionUtils.isEmpty(saleNameList) ? "" : String.join(",", saleNameList));
            resultList.add(saleRebatesRules);
        }
        return PageKit.startPage(resultList, saleRebatesRulesQuery.getPageNo(), saleRebatesRulesQuery.getPageSize());
    }

    @Override
    public SaleRebatesRulesDO selectRuleByCompany(String companyId, String siteId) {
        CompanySaleRebatesRulesDO companySaleRebatesRules = companySaleRebatesRulesService
                .selectRulesByCompanyId(companyId, siteId);
        if (ObjectUtils.isEmpty(companySaleRebatesRules)) {
            return null;
        }
        return this.selectDOById(companySaleRebatesRules.getRebatesRulesId(), siteId);
    }

    /**
     * 校验名称
     */
    private void checkName(String name, String rulesId, String siteId) {
        Example example = new Example(SaleRebatesRulesDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId)
                .andEqualTo("rulesName", name);
        if (!StringUtils.isEmpty(rulesId)) {
            example.and().andNotEqualTo("id", rulesId);
        }
        List<SaleRebatesRulesDO> saleRebatesRules = saleRebatesRulesDAO.selectByExample(example);
        if (!CollectionUtils.isEmpty(saleRebatesRules)) {
            throw new ParamException("规则名称重复");
        }
    }

    /**
     * 根据查询参数，构建example
     *
     * @param saleRebatesRulesQuery 查询参数
     * @param siteId                所属站点id
     * @return example
     */
    private Example buildExample(SaleRebatesRulesQuery saleRebatesRulesQuery, String siteId) {
        Example example = new Example(SaleRebatesRulesDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        // 排序
        ExampleKit.setExampleOrder(example, saleRebatesRulesQuery.getOrders());
        return example;
    }
}




